package com.jhws.business.appconfig.service;

import com.jhws.business.appconfig.bo.AppConfigType;
import com.jhws.core.db.BaseDao;
import com.jhws.core.exception.BizException;
import com.jhws.util.GetId;
import com.jhws.util.LogHelper;
import com.jhws.util.StringUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class AppConfigTypeService {
    @Resource
    private BaseDao BaseDao;

    /**
     * 保存类型
     *
     * @param appConfigType 类型信息
     */
    public void save(AppConfigType appConfigType) {
        List<AppConfigType> appConfigTypes = queryAppConfigTypeByWhere("where type_key='" + appConfigType.getTypeKey() + "' and parent_id='-1'");
        if (appConfigTypes != null && appConfigTypes.size() > 0 && !appConfigTypes.get(0).getId().equals(appConfigType.getId())) {
            throw new BizException("类型key已经存在！");
        }
        if (StringUtils.isEmpty(appConfigType.getId())) {
            appConfigType.setId(GetId.randomID());
        }
        if (StringUtils.isEmpty(appConfigType.getParentId())) {
            appConfigType.setParentId("-1");
        }
        appConfigType.setUpdateTime(new Date());
        BaseDao.saveOrUpdate(appConfigType);
    }

    /**
     * 查询类型信息
     *
     * @param param Map
     * @return 查询类型信息列表
     */
    @SuppressWarnings("unchecked")
    public Map<String, Object> queryAppConfigTypePage(Map param) {
        String hql = "from AppConfigType where 1=1 ";
        String typeNmame = MapUtils.getString(param, "typeNmame", "");
        if (StringUtils.isNotEmpty(typeNmame)) {
            hql += " and type_nmame = '" + typeNmame + "' ";
        }
        String typeKey = MapUtils.getString(param, "typeKey", "");
        if (StringUtils.isNotEmpty(typeKey)) {
            hql += " and type_key = '" + typeKey + "' ";
        }
        String parentId = MapUtils.getString(param, "parentId", "");
        if (StringUtils.isNotEmpty(parentId)) {
            hql += " and parent_id = '" + parentId + "' ";
        }
        return BaseDao.queryPage(hql);
    }

    /**
     * 条件查询类型
     *
     * @param where 条件
     * @return
     */
    public List<AppConfigType> queryAppConfigTypeByWhere(String where) {
        return BaseDao.findList("from AppConfigType " + where);
    }

    /**
     * 删除类型信息
     *
     * @param appConfigType 类型信息
     */
    public void deleteAppConfigType(AppConfigType appConfigType) {
        BaseDao.delete(appConfigType);
    }

    /**
     * 条件删除类型信息
     *
     * @param where 条件
     */
    public void deleteAppConfigType(String where) throws Exception {
        String sql = "delete from app_config_type " + where;
        LogHelper.e("aaaaaa---->   " + sql);
        BaseDao.executeBySql(sql);
    }
}
